<template>
  <a-modal
    :title="data.id ? $t('all.autotext919') : $t('all.autotext409')"
    :visible="innerVisible"
    :confirmLoading="confirmLoading"
    @ok="onSubmit"
    @cancel="cancel"
  >
    <!-- 新增表单 start -->
    <a-form-model
      ref="ruleForm"
      :rules="rules"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 15 }"
    >
      <a-form-model-item :label="$t('all.autotext645')">
        <span>{{ queryParam.type === 1 ? $t('all.autotext521.1') : $t('all.autotext521.2') }}</span>
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext1278')" prop="applyType">
        <a-input v-if="!data.id" v-model="form.applyType" :placeholder="$t('all.autotext1428')" />
        <span v-else>{{ form.applyType }}</span>
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext507')" prop="ptsTypeId" v-if="form.type === 2">
        <a-select v-model="form.ptsTypeId" mode="multiple" :placeholder="$t('all.autotext1215')">
          <a-select-option v-for="item in ptsTypesList" :key="item.id" :value="item.id">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext1297')" prop="visitStages" v-if="form.type === 2">
        <treeselect
          :defaultExpandLevel="Infinity"
          v-model="form.visitStages"
          :multiple="true"
          valueConsistsOf="LEAF_PRIORITY"
          :options="visitVersionList"
          :normalizer="normalizer"
          :nooptionstext="$t('all.autotext1353')"
          :placeholder="$t('all.autotext1348')"
          style="line-height: 1.5"
          sortValueBy="INDEX"
          @select="treeSelect"
          @deselect="treeDeselect"
        >
          <label slot="option-label" slot-scope="{ node }">
            {{ !node.isBranch ?  node.raw.name + ':' + node.raw.stage : node.raw.name }}
          </label>
        </treeselect>
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext750')" prop="amt">
        <div>
          <a-switch v-model="form.defaulted" @change="handleDefaultChange" />
          <a-input
            :min="0"
            :max="1000000000"
            v-model="form.amt"
            :placeholder="$t('all.autotext26')"
            style="width: 100%"
            :disabled="!form.defaulted"
            @input="(e) => (this.form.amt = $commonMethods.moneyCheck(e.target.value))"
          />
        </div>
      </a-form-model-item>
      <a-form-model-item
        :label="$t('all.autotext696')"
        v-if="!form.defaulted"
        :extra="$t('all.autotext169')"
        prop="cost"
      >
        <a-row>
          <a-col :span="10"><a-form-model-item prop="costMin"><a-input v-model="form.costMin" :placeholder="$t('all.autotext1527')"/></a-form-model-item></a-col>
          <a-col :span="4" style="text-align:center">{{ $t('all.autotext87') }}</a-col>
          <a-col :span="10"><a-form-model-item prop="costMax"><a-input v-model="form.costMax" :placeholder="$t('all.autotext1527')"/></a-form-model-item></a-col>
        </a-row>
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext1103')">
        <a-switch v-model="form.apv" />
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext983')">
        <a-input v-model="form.remark" type="textarea" :placeholder="$t('all.autotext983')" />
      </a-form-model-item>
    </a-form-model>
    <!-- 新增表单 end -->
  </a-modal>
</template>

<script>
import { add, listvisitVersion, updata, getPtsTypes } from '@/api/overview/cost'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import modalMixin from '@/utils/modal.mixin'

export default {
  props: ['data', 'queryParam'],
  components: { Treeselect },
  mixins: [modalMixin],
  data () {
    const validateCostMin = (rule, value, callback) => {
      if (!value) {
        callback()
        return true
      }
      if (/^(0|[1-9][0-9]*)(\.\d+)?$/.test(value) === false) {
        callback(new Error(this.$t('all.autotext209')))
        return false
      }
      const cost = parseFloat(value)
      const costMax = parseFloat(this.form.costMax)
      if (/^(\d+)(.\d{0,2})?$/g.test(value) === false) {
        callback(new Error(this.$t('all.autotext706')))
        return false
      }
      if (cost <= 0) {
        callback(new Error(this.$t('all.autotext209')))
        return false
      }
      if (cost > costMax) {
        callback(new Error(this.$t('all.autotext1018')))
      } else {
        callback()
      }
    }
    const validateCostMax = (rule, value, callback) => {
      if (!value) {
        callback()
        return true
      }
      if (/^(0|[1-9][0-9]*)(\.\d+)?$/.test(value) === false) {
        callback(new Error(this.$t('all.autotext209')))
        return false
      }
      const cost = parseFloat(value)
      const costMin = parseFloat(this.form.costMin)
      if (/^(\d+)(.\d{0,2})?$/g.test(value) === false) {
        callback(new Error(this.$t('all.autotext706')))
        return false
      }
      if (cost <= 0) {
        callback(new Error(this.$t('all.autotext209')))
        return false
      }
      if (cost < costMin) {
        callback(new Error(this.$t('all.autotext72')))
      } else {
        callback()
      }
    }
    return {
      proId: '',
      visitName: [],
      ptsTypesList: [],
      visitVersionList: [],
      confirmLoading: false,
      rules: {
        ptsTypeId: [{ required: true, message: this.$t('all.autotext1215'), trigger: 'blur' }],
        visitStages: [{ required: true, message: this.$t('all.autotext670'), trigger: 'blur' }],
        // 校验规则
        applyType: [
          { required: true, message: this.$t('all.autotext324'), trigger: 'change' },
          { min: 1, max: 50, message: '类目不能超过50位', trigger: 'change' }
        ],
        amt: [
          { required: false, trigger: 'change' },
          { pattern: /^\d{1,8}(\.\d{0,2}$)?/, message: this.$t('all.autotext346') }
        ],
        costMin: [
          { required: false, trigger: 'change' },
          { validator: validateCostMin, trigger: 'change' }
        ],
        costMax: [
          { required: false, trigger: 'change' },
          { validator: validateCostMax, trigger: 'change' }
        ]
      },
      form: {},
      normalizer (node) {
        return {
          id: node.id,
          label: node.name,
          children: node.visitList
        }
      }
    }
  },
  created () {
    const pd = localStorage.getItem('CURRENT_PROID')
    if (pd) {
      this.proId = parseInt(pd)
    }
  },
  methods: {
    treeSelect (node) {
      this.visitName.push(node.name)
    },
    treeDeselect (node) {
      let index = this.visitName.findIndex(item => item === node.name)
      this.visitName.splice(index, 1)
    },
    async modalUpdated () {
      if (this.queryParam.type === 2) {
        this.visitVersionList = await listvisitVersion({ proId: this.proId })
        this.ptsTypesList = await getPtsTypes({ proId: this.proId })
      }
      if (!this.data.id) {
        this.form = { type: this.queryParam.type, ptsTypeId: [] }
        if (this.queryParam.type === 2) {
          const arr = []
          const visitName = []
          this.visitVersionList.forEach(v => {
            v.visitList.forEach(m => {
              arr.push(m.id)
              visitName.push(m.name)
            })
          })
          this.visitName = visitName
          this.form.visitStages = arr
          this.form.ptsTypeId = this.ptsTypesList.map(v => v.id)
        }
        return
      }
      this.form = {
        ...this.data,
        ptsTypeId: this.data.ptsTypeId ? this.data.ptsTypeId.split(',').map(item => Number(item)) : [],
        visitStages: this.data.visitStages ? this.data.visitStages.split(',').map(Number) : []
      }
      delete this.form.visitVersionRecords
    },
    handleDefaultChange (e) {
      if (!e) this.form.amt = ''
    },
    // 新增提交
    onSubmit () {
      this.$refs.ruleForm.validate(valid => {
        if (!valid) return
        this.confirmLoading = true
        const req = JSON.parse(JSON.stringify(this.form))
        req.defaulted = +Boolean(req.defaulted)
        req.apv = +Boolean(req.apv)
        req.amt = Number(req.amt || 0).toFixed(2)
        if (req.type === 2) {
          const visitVersion = []
          req.visitStages.forEach(selectId => {
            for (const version of this.visitVersionList) {
              const tar = version.visitList.find(visit => visit.id === selectId)
              if (tar) {
                visitVersion.push(version.id)
                break
              }
            }
          })
          req.visitStages = req.visitStages.toString()
          req.visitVersion = [...new Set(visitVersion)].toString()
          if (req.ptsTypeId) {
            req.ptsTypeId = req.ptsTypeId.join(',')
          }
        }

        if (!this.data.id) {
          // 新增
          req.proId = this.proId // 新增状态多传一个proId
          add({
            ...req,
            ptsTypeIdDesc: this.form.ptsTypeId.map(val => this.ptsTypesList.find(item => Number(item.id) === Number(val)).name).join(','),
            visitStagesDesc: this.visitName.join(',')
          }).then(res => {
            this.$message.success(this.$t('all.autotext470'))
            this.confirmLoading = false
            this.$emit('refresh')
            this.innerVisible = false
          }).catch(_ => {
            this.confirmLoading = false
          })
        } else {
          updata({
            ...req,
            ptsTypeIdDesc: this.form.ptsTypeId.map(val => this.ptsTypesList.find(item => Number(item.id) === Number(val)).name).join(','),
            visitStagesDesc: this.visitName.join(','),
            beforeData: JSON.stringify(this.data)
          }).then(res => {
            this.$message.success(this.$t('all.autotext470'))
            this.confirmLoading = false
            this.$emit('refresh')
            this.innerVisible = false
          }).catch(_ => {
            this.confirmLoading = false
          })
        }
      })
    },
    cancel () {
      this.$refs.ruleForm.resetFields()
      this.innerVisible = false
    }
  }
}
</script>

